/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    DatePickerAndroid,
    DatePickerIOS,
    Platform,
    InteractionManager,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import ImageCropPicker from 'react-native-image-crop-picker';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class EditActive extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.state = {
            startTime:'开始时间',
            startTimeStamp:'',
            endTime:'结束时间',
            endTimeStamp:'',
            imgUriList:[],
            imgDataList:[],
            title:'',
            content:'',
            personNum:'',
            activeData:{},
            activeId:this.props.navigation.state.params.activeId,
            changeImage:false,
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getActiveDetails();
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    renderImg(){
        var list = this.state.imgUriList;
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(i)}>
                            <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                            <Image style={{width:60,height:60}} source={{uri:item.path}}/>               
                        </TouchableOpacity>
                        
                    </View>
                )                
            })
        )
    }
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'修改活动'} 
                    leftPress={()=>this.goBack()}
                    rightText={'完成'}
                    rightTextStyle={{color:'#fff'}}
                    rightTextPress={()=>this.editFinish()}/>
                <ScrollView>
                    <View style={{backgroundColor:'#fff'}}>
                        <TextInput
                            placeholder={'活动标题'}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text)=>this.getTitle(text)}
                            defaultValue={this.state.title}
                            onBlur={()=>this.editData('title')}/>
                    </View>
                    <View style={{backgroundColor:'#fff',marginTop:10}}>
                        <TextInput placeholder={'活动内容'}
                            underlineColorAndroid={'transparent'}
                            textAlignVertical={'top'}
                            multiline={true}
                            numberOfLines={7}
                            onChangeText={(text)=>this.getContent(text)}
                            defaultValue={this.state.content}
                            onBlur={()=>this.editData('content')}/>
                        <View style={{flexDirection:'row',flexWrap:'wrap',paddingLeft:10,paddingBottom:10}}>
                            {this.renderImg()}
                            <TouchableOpacity onPress={()=>this.choseImg()} style={{marginBottom:10,width:60,height:60,marginTop:10}}>
                                <ImageWrapper width={60} height={60} icon={'addImg'}/>
                            </TouchableOpacity>
                        </View>
                        
                    </View>
                    <View style={{height:30,justifyContent:'center',paddingLeft:10,marginTop:10,backgroundColor:'#fff'}}>
                        <Text>活动时间</Text>
                    </View>
                    <View style={{flexDirection:'row',backgroundColor:'#fff',height:30}}>
                        <View style={[styles.timeTextBox,{flex:1}]}>
                            <Text onPress={this.showPicker.bind(this, 'preset', 1)}>{this.state.startTime}</Text>
                        </View>
                        <View style={[styles.timeTextBox,{width:40}]}>
                            <Text>~</Text>
                        </View>
                        <View style={[styles.timeTextBox,{flex:1}]}>
                            <Text onPress={this.showPicker.bind(this, 'preset', 2)}>{this.state.endTime}</Text>
                        </View>
                    </View>
                    <View style={{backgroundColor:'#fff',marginTop:10}}>
                        <TextInput
                            placeholder={'参与人数'}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text)=>this.getPersonNum(text)}
                            defaultValue={this.state.personNum+''}
                            onBlur={()=>this.editData('person_num')}/>
                    </View>
                    <TouchableOpacity onPress={()=>this.sss()}><Text>3333</Text></TouchableOpacity>
                </ScrollView>
                
            </View>
        )
    }
    sss(){
        alert(JSON.stringify(this.state.imgDataList))
    }

    goBack(){
        this.props.navigation.goBack();
    }

    getActiveDetails(){
        var $this = this;
        shopService.activityIdInfo(function(data){
            alert(JSON.stringify(data))
            if(data.code==10000){
                var arr = [];
                var dataArr = [];
                var list = data.data.img;
                var len = list.length;
                for(var i=0;i<len;i++){
                    if(list[i]!=''){
                        var obj = {};
                        obj.path = ('http://peita.oss-cn-beijing.aliyuncs.com/'+list[i]);
                        arr.push(obj);
                        dataArr.push(obj);
                    }
                    
                }
                var start = new Date(data.data.start_time*1000);
                var startText = start.getFullYear()+'-'+(start.getMonth()>8?(start.getMonth()+1):('0'+(start.getMonth()+1)))+'-'+(start.getDate()>9?start.getDate():('0'+start.getDate()));
                var end = new Date(data.data.end_time*1000);
                var endText = end.getFullYear()+'-'+(end.getMonth()>8?(end.getMonth()+1):('0'+(end.getMonth()+1)))+'-'+(end.getDate()>9?end.getDate():('0'+end.getDate()));
                $this.setState({
                    startTime:startText,
                    startTimeStamp:data.data.start_time,
                    endTime:endText,
                    endTimeStamp:data.data.end_time,
                    imgUriList:arr,
                    imgDataList:dataArr,
                    title:data.data.title,
                    content:data.data.content,
                    personNum:data.data.person_num,
                    activeData:data.data,
                })
            }
        },$this.state.activeId,$this.token)
    }

    selectItem(index){
        var imgList = this.state.imgUriList;
        var dataList = this.state.imgDataList;
        imgList.splice(index,1);
        dataList.splice(index,1);
        this.setState({
            imgUriList:imgList,
            imgDataList:dataList,
            changeImage:true,
        })
    }

    getTitle(text){
        this.setState({
            title:text
        })
    }

    getContent(text){
        this.setState({
            content:text
        })
    }

    getPersonNum(text){
        this.setState({
            personNum:text
        })
    }

    async showPicker(stateKey, staturs) {
        try {
            var newState = {};
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: new Date(),
                mode:'spinner'
            });      
            if (action === DatePickerAndroid.dismissedAction) {
                newState[stateKey + 'Text'] = 'dismissed';
            } else {
                var date = new Date(year, month, day);
                newState[stateKey + 'Text'] = date.toLocaleDateString();
                newState[stateKey + 'Date'] = date;
                var newDate = '' + year + '-' + ((month+1)>9?(month+1):'0'+(month+1)) + '-' + (day>9?day:'0'+day);
                if(staturs==1){
                    await this.setState({
                        startTime:newDate,
                        startTimeStamp:date.getTime()/1000,
                    })
                    this.editData('start_time');
                }else if(staturs==2){
                    await this.setState({
                        endTime:newDate,
                        endTimeStamp:date.getTime()/1000,
                    })
                    this.editData('end_time');
                }
            }

            this.setState(newState);
        } catch ({code, message}) {
            console.warn(`Error in example '${stateKey}': `, message);
        }
    }

    // 选择头像上传
    choseImg(){
        var $this = this;
        if(this.state.imgUriList.length==5){
            return;
        }
        ImageCropPicker.openPicker({
            multiple: true,
            maxFiles: 9,
            mediaType: 'photo'
        }).then(images => {
            var len = images.length;
            var arr = [];
            for(var i=0;i<len;i++){
                var source = {};
                if (Platform.OS === 'android') {
                    source = {path: images[i].path, isStatic: true};
                    arr.push(source);
                } else {
                    source = {path: images[i].path.replace('file://', ''), isStatic: true};
                    arr.push(source);
                }
            }
            var uriArr = $this.state.imgUriList;
            var dataArr = $this.state.imgDataList;
            uriArr = uriArr.concat(arr);
            dataArr = dataArr.concat(images);
            $this.setState({
                imgUriList:uriArr,
                imgDataList:dataArr,
                changeImage:true,
            });
        }).catch((err)=> {
                console.log(err);
            });
                
    }

    editData(name){
        var obj = {};
        typeObj = {
            'title':1,
            'content':2,
            'start_time':3,
            'end_time':4,
            'person_num':5,
        }
        stateObj = {
            'title':'title',
            'content':'content',
            'start_time':'startTimeStamp',
            'end_time':'endTimeStamp',
            'person_num':'personNum',
        }
        obj.id = this.state.activeData.ac_id;
        obj.access = this.token;
        if(this.state.activeData[name]!=this.state[stateObj[name]]){
            obj.type = typeObj[name];
            obj[name] = this.state[stateObj[name]];
            shopService.activityIdSave(function(data){
                alert(JSON.stringify(data));
            },obj)
        }
    }

    editFinish(){
        var $this = this;
        var obj = {};
        obj.id = this.state.activeData.ac_id;
        obj.access = this.token;
        if(this.state.changeImage){
            var arr = [];
            var len = this.state.imgDataList.length;
            var imgText = '';
            var index = 1;
            for(var i=0;i<len;i++){
                if(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//.test(this.state.imgDataList[i].path)){
                    imgText+=this.state.imgDataList[i].path.replace(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//g,'')+',';
                }else{
                    arr['img'+index] = this.state.imgDataList[i].path;
                    index++;
                }
                
            }

            if(len>0){
                if(arr['img1']){
                    shopService.upFile(function(data){
                        alert(JSON.stringify(data));
                        if(data.code==10000){
                            obj.img = imgText+data.data;
                            obj.type = 6;
                            shopService.activityIdSave(function(data){
                                if(data.code==10000){
                                    // $this.goBack();
                                    // return;
                                    alert('1'+JSON.stringify(data))
                                }
                            },obj)
                        }
                    },arr,$this.token)
                }else{
                    obj.img = imgText;
                    obj.type = 6;
                    shopService.activityIdSave(function(data){
                        if(data.code==10000){
                            alert('2'+JSON.stringify(data))
                            // $this.goBack();
                            // return;
                        }
                    },obj)
                }
                
            }
            
        }
        // this.goBack();
    }

}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    timeTextBox:{
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#fff'
    }

});